package org.example.server8001.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.SystemDemo.core.Result;
import org.example.SystemDemo.comment.enity.HostInfo;
import org.example.SystemDemo.utils.JSONUtil;
import org.example.server8001.service.InfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@RestController
@RequestMapping("/relay")
public class RelayController {

    @Autowired
    private InfoService infoService;

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/{type}/{path}",method = RequestMethod.GET)
    public Result<?> Relay(@PathVariable String type, @PathVariable String path, @RequestParam("index") Long index){
        final HostInfo one = infoService.getOne(Wrappers.<HostInfo>lambdaQuery().eq(HostInfo::getId, index));
        if(!Objects.isNull(one)){
            if (!one.isConnectStatus()){
                return Result.error("请求目标服务器离线中");
            }
            String url = String.format("http://%s:%s/%s/%s",one.getHostIp(),one.getRunPort(),type,path);
            return Result.ok(restTemplate.getForObject(url,Object.class));
        }

        return Result.error("index不存在");
    }
}
